<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input @clear="getUserList" clearable v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="dialogVisible=true" type="primary">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch @change="stateChange(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="item">
            <el-row>
              <el-button @click="editUser(item.row.id)" size="mini" type="primary" icon="el-icon-edit" circle></el-button>
              <el-button @click="delUser(item.row.id)" size="mini" type="danger" icon="el-icon-delete" circle></el-button>

              <el-tooltip
                :enterable="false"
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
              >
                <el-button size="mini" type="warning" icon="el-icon-setting" circle></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      @close="addDialogClosed"
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%">
      
      <!-- 内容主题区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialog"
      width="70%">
      @close="editDialogClosed"  
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名称" >
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialog = false">取 消</el-button>
          <el-button @click="subEdit" type="primary">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule,value,cb)=>{
        var reg =  /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g
        if(reg.test(value)){
          return cb()
        }else{
          cb(new Error('邮箱格式不符合要求'))
        }
      }
    var checkMobile = (rule,value,cb)=>{
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
       if(reg.test(value)){
          return cb()
        }else{
          cb(new Error('手机号码格式不符合要求'))
        }
    }  
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      userList: [],
      dialogVisible:false,
      addForm:{
        username:'',
        password:'',
        mobile:'',
        email:''
        },
      addFormRules:{
        username:[
          {required:true,message:'请输入用户名',trigger:'blur'},
          {min:3,max:10,message:'用户名的长度在3-10个字符之间',trigger:'blur'}
        ],
        password:[
          {required:true,message:'请输入密码',trigger:'blur'},
          {min:3,max:10,message:'用户名的长度在3-10个字符之间',trigger:'blur'}
        ],
        mobile:[
          {required:true,message:'请输入手机号',trigger:'blur'},
          {validator:checkMobile,trigger:'blur'}
        ],
        email:[
          {required:true,message:'请输入邮箱',trigger:'blur'},
          {validator:checkEmail,trigger:'blur'}
        ]
      },
      editDialog:false,
      editForm:{},
      editFormRules:{
        mobile:[
          {required:true,message:'请输入手机号',trigger:'blur'},
          {validator:checkMobile,trigger:'blur'}
        ],
        email:[
          {required:true,message:'请输入邮箱',trigger:'blur'},
          {validator:checkEmail,trigger:'blur'}
        ]
      }
    }
  },

  methods: {
    
    async getUserList() {
      var { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status != 200) {
        return this.$message.error('服务器错误')
      }
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(this.userList)
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    handleSizeChange(val) {
      // console.log(val)
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    async stateChange(userinfo){
      // console.log(userinfo)
      var {data:res} =  await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if(res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('用户状态切换失败')
      }
        this.$message.success('用户状态切换成功')
    },
    addDialogClosed(){
      // console.log(this.$refs)
      this.$refs.addFormRef.resetFields()
    },
    adduser(){
      this.$refs.addFormRef.validate(async flag=>{
        if(flag){
          var {data:res} = await this.$http.post('users',this.addForm)
          console.log(res)
          if(res.meta.status == 201) {
            this.$message.success('添加用户成功')
          }else{
            this.$message.error('添加用户失败')
          }
          this.dialogVisible = false
          this.getUserList()
        }
      })
    },
    async editUser(id){
      this.editDialog = true
      // console.log(id)
      var {data:res} = await this.$http.get('users/'+id)
      // console.log(res)
      if(res.meta.status == 200){
        this.editForm = res.data
      }else{
        this.$message.error('服务器错误')
      }
      this.dialogVisible = false
    },
    editDialogClosed(){
      this.$refs.editFormRef.resetFields()
    },
    subEdit(){
      this.$refs.editFormRef.validate(flag=>{
        if(flag){
          console.log("修改成功")
        }
      })
      return
      this.editDialog = false
    },
    async delUser(id){
      var res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err=>err)
      // console.log(res)
      if(res == 'confirm'){
        // console.log('修改用户成功')
        var {data:res} = await this.$http.delete('users/'+id)
        // console.log(res)
        if(res.meta.status == 200){
          this.$message.success('删除用户成功')
          this.getUserList()
        }else{
          this.$message.error('删除用户失败')
        }
      }else{
        this.$message.error('用户取消删除')
      }
    }
  },

  created() {
    this.getUserList()
  }
}
</script>

<style lang='less' scoped>
</style>
